package com.tjbklx1.redis.chap05;

import java.util.Date;
import java.util.List;

import com.tjbklx1.redis.JedisUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

/**
 * 案例,利用redis 处理日志
 * @author tjbklx1
 * @date 2018-12-5
 */
public class App51_Log {

	public static void main(String[] args) {
		Jedis conn = JedisUtil.getJedisWithDB();
		new App51_Log().testLogRecent(conn);
	}

	private void testLogRecent(Jedis conn) {
		System.out.println("\n----- testLogRecent -----");
		System.out.println("Let's write a few logs to the recent log");
		//写五条日志
		for (int i = 0; i < 5; i++) {
			logRecent(conn, "test", "this is message " + i);
		}
		//查询日志
		List<String> recent = conn.lrange("recent:test:info", 0, -1);
		System.out.println("The current recent message log has this many messages: " + recent.size());
		System.out.println("Those messages include:");
		for (String message : recent) {
			System.out.println(message);
		}
		assert recent.size() >= 5;

	}

	/**
	 * 以日志级别是INFO 的方式写日志
	 * @param conn
	 * @param name 日志的名字
	 * @param message 日志的内容
	 */
	public void logRecent(Jedis conn, String name, String message) {
		logRecent(conn, name, message, MyLogger.INFO); // 日志级别是INFO 
	}

	/**
	 * 
	 * @param conn
	 * @param name 日志的名字
	 * @param message 日志的内容
	 * @param severity 日志级别
	 */
	public void logRecent(Jedis conn, String name, String message, String severity) {
		String destination = "recent:" + name + ':' + severity; // 组织日志的KEY
		//PIPELINE
		Pipeline pipe = conn.pipelined(); 
		pipe.lpush(destination, MyLogger.TIMESTAMP.format(new Date()) + ' ' + message); //增加日志
		pipe.ltrim(destination, 0, 99); //删除多余日志,只保留前100条
		pipe.sync();
	}
}
